package com.ziiwee.reduce.commons.utils;

import com.ziiwee.reduce.commons.lang.ReflectException;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class BeanUtil {

    /**
     * 调用字段 set 方法
     *
     * @param object
     * @param name
     * @param value
     */
    public static void setValue(Object object, String name, Object value) {
        try {
            PropertyDescriptor descriptor = new PropertyDescriptor(name, object.getClass());
            Method writeMethod = descriptor.getWriteMethod();
            writeMethod.invoke(object, value);
        } catch (Exception e) {
            throw new ReflectException(e.getMessage(), e);
        }
    }

    /**
     * 调用字段 get 方法
     *
     * @param object
     * @param name
     * @return
     */
    public static Object getValue(Object object, String name) {
        try {
            PropertyDescriptor descriptor = new PropertyDescriptor(name, object.getClass());
            Method readMethod = descriptor.getReadMethod();
            return readMethod.invoke(object);
        } catch (Exception e) {
            throw new ReflectException(e.getMessage(), e);
        }
    }

    /**
     * 通过字段名获取字段（包括所有父类）
     *
     * @param aClass
     * @param name
     * @return
     */
    public static Field getField(Class<?> aClass, String name) {
        try {
            return aClass.getDeclaredField(name);
        } catch (NoSuchFieldException e) {
            if (!Object.class.equals(aClass.getSuperclass())) {
                return getField(aClass.getSuperclass(), name);
            }
        }
        return null;
    }

}
